import { instanceToPlain } from 'class-transformer'

/** 数据转化工具类 */
export class TransformUtil {
  /** 序列化 */
  static serialize<T>(value: T) {
    return instanceToPlain(value)
  }

  /** 列表转树形 */
  static listToTree(list: any[], fieldNames: Omit<ITreeNode, 'children'>) {
    const { title, key, parentKey } = fieldNames
    const temp = list.map<ITreeNode>(v => ({
      title: v[title],
      key: v[key],
      parentKey: v[parentKey],
      children: []
    }))
    const hash = new Map<string, ITreeNode>()
    const tree = [] as ITreeNode[]

    temp.forEach(v => {
      hash.set(v.key, v)
      const parent = hash.get(v.parentKey)

      if (!parent) {
        tree.push(v)
      } else {
        parent.children.push(v)
      }
    })

    return tree
  }
}
